<template>
  <div>
    <div class="card flex flex-row gap-2">
      <el-input v-model="queryText" placeholder="请输入查询内容" style="width: 200px"></el-input>
      <el-button type="primary" @click="refresh">查询</el-button>
      <el-button type="primary" @click="showDictConfig(undefined)">新增</el-button>
      <el-button type="primary">保存</el-button>
      <el-button type="primary" @click="updateDictConfig">更新字典配置</el-button>
    </div>
    <div class="card flex flex-col gap-2" style="margin-top: 10px">
      <vxe-table :data="paginationRes.data" :height="tableHeight">
        <vxe-column type="seq" title="序号" width="50" />
        <vxe-column field="dictType" title="字典类型" width="140">
          <template #default="{ row }">
            <el-tag v-if="row.dictType === EnumDictType.基本表" type="primary" size="small" effect="dark">表</el-tag>
            <el-tag v-else type="success" size="small" effect="dark">视图</el-tag>
          </template>
        </vxe-column>
        <vxe-column field="dictName" title="字典名称" width="200" />
        <vxe-column field="tableName" title="表名称" width="280" />
        <vxe-column field="createOperatorName" title="创建人" width="140" />
        <vxe-column field="createDate" title="创建时间" width="160">
          <template #default="{ row }">
            {{ dayjs(row.createDate).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
        </vxe-column>
        <vxe-column title="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="showDictConfig(row.dictCode)">详情</el-button>
            <el-button type="danger" size="small" @click="removeDictConfig">删除</el-button>
          </template>
        </vxe-column>
      </vxe-table>
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="paginationRes?.total"
        :page-size="paginationReq.pageSize"
        :page-sizes="[10, 20, 30, 40]"
        :current-page="paginationReq.currentPage"
        style="margin-top: 10px"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog v-model="visible" title="字典详情" width="1200">
      <div style="display: flex; flex-direction: column; gap: 10px">
        <title-bar>字典信息</title-bar>
        <el-descriptions border :column="2">
          <el-descriptions-item label="表名称" label-width="100">
            {{ dictConfig?.tableName }}
          </el-descriptions-item>
          <el-descriptions-item label="字典名称" label-width="100">
            {{ dictConfig?.dictName }}
          </el-descriptions-item>
          <el-descriptions-item label="字典类型" label-width="100">
            <el-tag v-if="dictConfig?.dictType === EnumDictType.基本表" type="primary" size="small" effect="dark">
              表
            </el-tag>
            <el-tag v-else type="success" size="small" effect="dark">视图</el-tag>
          </el-descriptions-item>
        </el-descriptions>

        <title-bar>
          <span>字典明细</span>
        </title-bar>
        <vxe-table
          ref="itemTableRef"
          :data="dictConfig?.items || []"
          height="380"
          :edit-config="{ trigger: 'click', mode: 'cell' }"
        >
          <vxe-column type="seq" title="序号" width="50" />
          <vxe-column field="columnName" title="数据库字段名称" width="200" :edit-render="{}">
            <template #edit="{ row }">
              <el-input v-if="row.status === -1" v-model="row.columnName" placeholder="请输入数据库字段名称" />
              <span v-else>{{ row.columnName }}</span>
            </template>
          </vxe-column>
          <vxe-column field="displayName" title="显示名称" width="240" :edit-render="{}">
            <template #edit="{ row }">
              <el-input v-model="row.displayName" placeholder="请输入显示名称" />
            </template>
          </vxe-column>
          <vxe-column field="displayWidth" title="显示宽度" width="160" :edit-render="{}">
            <template #edit="{ row }">
              <el-input-number v-model="row.displayWidth" :min="120" placeholder="请输入显示宽度" />
            </template>
          </vxe-column>
          <vxe-column field="displaySort" title="显示顺序" width="140" :edit-render="{}">
            <template #edit="{ row }">
              <el-input-number v-model="row.displaySort" :min="0" placeholder="请输入显示顺序" />
            </template>
          </vxe-column>
          <vxe-column field="easySearcher" title="便捷搜索" width="100" :edit-render="{}">
            <template #edit="{ row }">
              <el-checkbox v-model="row.easySearcher" :true-value="1" :false-label="0" />
            </template>
            <template #default="{ row }">
              <el-checkbox v-model="row.easySearcher" :true-value="1" :false-label="0" />
            </template>
          </vxe-column>
          <vxe-column field="editable" title="是否可编辑" width="100" :edit-render="{}">
            <template #edit="{ row }">
              <el-checkbox v-model="row.editable" :true-value="1" :false-label="0" />
            </template>
            <template #default="{ row }">
              <el-checkbox v-model="row.editable" :true-value="1" :false-label="0" />
            </template>
          </vxe-column>
          <vxe-column title="操作" fixed="right" width="100">
            <template #default="{ row }">
              <el-button type="danger" size="small" @click="removeItem(row)">删除</el-button>
            </template>
          </vxe-column>
        </vxe-table>
        <div style="display: flex; flex-direction: row; justify-content: space-between">
          <div>
            <el-button type="danger" @click="visible = false">关闭</el-button>
            <el-button type="danger" @click="removeDictConfig">删除字典</el-button>
          </div>
          <div>
            <el-button type="primary" @click="saveDict">保存</el-button>
            <el-button type="primary" @click="addItem">新增字段</el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { ElMessage, ElMessageBox, dayjs } from 'element-plus'
import type { VxeTableInstance } from 'vxe-table'
import type { DictConfigItem } from '@/api/system/dict'
import { DictAPIs, EnumDictName, EnumDictType, type DictConfig } from '@/api/system/dict'
import type { PaginationCommon, PaginationRes } from '@/api/common'

//#region 主界面
const queryText = ref('')
const paginationReq = ref<PaginationCommon>({
  currentPage: 1,
  pageSize: 10,
})

const paginationRes = ref<PaginationRes<DictConfig>>({
  data: [],
  total: 0,
})

const dictConfig = ref<DictConfig | undefined>(undefined)

watch(
  () => [queryText.value, paginationReq.value.currentPage, paginationReq.value.pageSize],
  async () => {
    await getData()
  }
)

const tableHeight = computed(() => {
  return window.innerHeight - 320
})

// 分页大小改变
const handleSizeChange = (val: number) => {
  paginationReq.value.pageSize = val
}

// 分页当前页改变
const handleCurrentChange = (val: number) => {
  paginationReq.value.currentPage = val
}

// 查询
const refresh = () => {
  paginationReq.value.currentPage = 1
  paginationReq.value.pageSize = 10
  getData()
}

// 获取字典配置数据
const getData = async () => {
  paginationRes.value = await DictAPIs.getDataByPagination({
    dictName: EnumDictName.字典配置,
    queryText: queryText.value,
    currentPage: paginationReq.value.currentPage,
    pageSize: paginationReq.value.pageSize,
    isPagination: true,
  })
}
//#endregion

//#region 详情
const visible = ref(false)
const itemTableRef = ref<VxeTableInstance<DictConfigItem>>()
// 显示字典明细
const showDictConfig = async (dictName?: EnumDictName) => {
  if (dictName == undefined || dictName == null) {
    // dictConfig.value = { editStatus: true, dictName, dictType: EnumDictType.基本表, items: [] }
  } else {
    dictConfig.value = await DictAPIs.getDictConfig(dictName)
  }

  visible.value = true
}

// 增加项目
const addItem = () => {
  const $table = itemTableRef.value
  if ($table) {
    $table.insert({
      displayWidth: 100,
      editStatus: true,
      displaySort: 1,
      easySearcher: 1,
      editable: 1,
    })
  }
}

// 删除项目
const removeItem = (row: DictConfigItem) => {
  const $table = itemTableRef.value
  if ($table) {
    $table.remove(row)
  }
}

// 删除字典
const removeDictConfig = async () => {
  if (dictConfig.value?.editStatus == true) {
    /*    dictConfig.value = {
      editStatus: true,
      items: [],
    } */
  } else {
    ElMessageBox.confirm('是否删除字典配置信息?', '提示', {
      confirmButtonText: '是',
      cancelButtonText: '否',
      type: 'warning',
    }).then(async () => {
      /*  if (dictConfig.value.dictName === undefined) {
        ElMessage.warning('')
        return
      }
      await DictAPIs.removeDictConfig(dictConfig.value.dictCode) */
    })
  }
  visible.value = false
  ElMessage.success('删除成功')
}

// 保存字典
const saveDict = async () => {
  const $table = itemTableRef.value
  if (!$table) {
    return
  }

  ElMessage.success('字典配置保存成功')
}

// 重载字典配置
const updateDictConfig = async () => {
  ElMessageBox.confirm('是否重载字典配置?', '提示', {
    confirmButtonText: '是',
    cancelButtonText: '否',
    type: 'warning',
  }).then(async () => {
    await DictAPIs.reloadDictConfig()
    ElMessage.success('字典配置重置成功')
  })
}
//#endregion
</script>

<style lang="scss" scoped></style>
